<?php
declare (strict_types=1);

namespace app\common\tool;

use Psr\Http\Message\ResponseInterface;

class Response
{
    protected $response;

    protected $data = [];

    public function __construct(ResponseInterface $response)
    {
        $this->response = $response;
    }

    public function toArray(): array
    {
        try {
            if (empty($this->data)) {
                if ('' === $content = (string)$this->response->getBody()) {
                    throw new \Exception('响应参数为空');
                }
                $this->data = json_decode($content, true);
            }
            return $this->data;
        } catch (\Exception $e) {
            throw $e;
        }
    }

    public function isSuccess(): bool
    {
        return $this->response->getStatusCode() == 200;
    }
}